/* Common document ready function for discussion plugin.
 *
 * So far connected hooks consist only of add subscriber click.
 */
$(document).ready(function() {

    /* Common subscriber manipulation hook
     *
     * Parses through the inputted string user has given and adds the resulting user names into
     * the subscribers list. Duplicates are dropped out in actual POST which is done when user
     * wants to save the changes. User name length is checked before doing POST (and after it
     * as well), and execution is stopped if a too long username is found.
     */
    $("#addsubscriber").click(function() {
        var subscriber = null;
        var found = false;
        var subs = null;

        subscriber = $("input[name=unregistered_subscribers]").val();

        if (subscriber === "" || subscriber == null) {
            return false;
        }

        subs = subscriber.split(/[\s,;]+/);

        /* No delimeters at all in the string */
        if (subs === subscriber) subs = [subscriber];

        for (var i = 0; i < subs.length; i++) {
            if (subs[i].length > 150) {
                alert ("Subscriber name is too long (more than 150 characters)!");
                return false;
            }

            $("#nosubs").css("display","none");
            $("#subscribers").css("display","block");
            $("#subscribers").append(new Option (subs[i], subs[i], true, true));
        }

        $("input[name=unregistered_subscribers]").val("");
    });
});

/* AJAX function that changes value of attribute <name> of item with id <id> to
value <value>. <url> is URL of AJAX request handler. */
function change_attribute(url, name, value)
{
  var callback = function(extra) {
    return function (data, text_status){
      $('body').css('cursor','default');
      if (text_status == "success")
      {
        if (extra.name == 'status.solved'){
          if (extra.value == false){
            var text = $("#\\[SOLVED\\]");
            // if visualstatuses are localized, falling back to reload
            if (text.length > 0){
              text.remove();
            }
            else{
              window.location.reload(false);
            }
          }
          else{
            $("#topic_subject").prepend("<span style='font-weight:bold;float:left;' id='[SOLVED]'>[SOLVED]</span>")
          }
        }
        else if (extra.name == 'status.locked'){
          var messageAddBox = $('#messageaddbox');
          if (extra.value == false){
            if (messageAddBox.length > 0){
              var text = $("#\\[LOCKED\\]");
                // if visualstatuses are localized, falling back to reload
              if (text.length > 0){
                text.remove();
                messageAddBox.show();
                // scrolling so that the perceived position doesn't change
                window.scrollBy(0, messageAddBox.height());
              }
              else{
                window.location.reload(false);
              }
            }
            else{
              // messageaddbox not in DOM, reloading
              window.location.reload(false);
            }
          }
          else{
            $("#topic_subject").prepend("<span style='font-weight:bold;float:left;' id='[LOCKED]'>[LOCKED]</span>")
            // scrolling so that the perceived position doesn't change
            window.scrollBy(0, -$(messageAddBox).height());
            messageAddBox.hide();
          }
        }
        else if (extra.name == 'important'){
          if (extra.value == false){
            var text = $("#\\[STICKY\\]");
            // if visualstatuses are localized, falling back to reload
            if (text.length > 0){
              text.remove();
            }
            else{
              window.location.reload(false);
            }
          }
          else{
            $("#topic_subject").prepend("<span style='font-weight:bold;float:left;' id='[STICKY]'>[STICKY]</span>")
          }
        }
      }
    }
  }

  var arguments = {'discussion_action' : 'edit-attribute',
    'name' : name,
    'value' : value,
    '__FORM_TOKEN': $('input[name="__FORM_TOKEN"]')[0].value};

  $('body').css('cursor','progress');
  $.post(url, arguments, callback(arguments));
}

function subscription_select(authname, subscribe)
{
  $("select#subscribers option[value='" + authname + "']").attr("selected",
    subscribe ? "selected" : "");
}

function subscribe_user(url, authname, subscribe)
{
  function callback(data, text_status)
  {
    // change button text
    var content = $($('<p />').html(data).html()).html()
    $("#subscribe").attr('value',content);
    // update subscriber list
    var name = $("<span>"+authname+"</span>").text();
    if (content == "Unsubscribe"){
      $("input[name=unregistered_subscribers]").val(name);
      $("#addsubscriber").click();
    }
    else if (content == "Subscribe"){
      $("#subscribers > option[value='"+name+"']").remove();
      if ($("#subscribers > option").length == 0) {
        $("#nosubs").show();
        $("#subscribers").hide();
      }
    }
    else{
        // localized strings, falling back to refresh
        window.location.reload(false);
    }
  }

  arguments = {'discussion_action' : 'subscribe-toggle',
    '__FORM_TOKEN': $('input[name="__FORM_TOKEN"]')[0].value};
  $.post(url, arguments, callback);


}

/* Hides/reveals all "Reply" and "Quote" links on page when topic is
locked/unlcoked */
function lock_topic(value)
{
  $("a.reply, a.quote").css("display", value ? "none" : "");
}
